﻿using CgdataBase;
using FolderCompare.ViewModels;
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace FolderCompare.Views
{
    public partial class MainWindow : Window
    {
        private Prism.Events.IEventAggregator Aggregator => EventHelper.Aggregator;

        public MainWindow()
        {
            InitializeComponent();
            DataContext = new MainWindowViewModel(this);
            WindowController.UpdateWindowConfig(this, this.GetType());
            this.Loaded += (s, e) =>
            {
                CheckAppVersion();

                var scroll1 = FindVisualChildren<ScrollViewer>(LeftList).First();
                var scroll2 = FindVisualChildren<ScrollViewer>(RightList).First();
                scroll1.ScrollChanged += (s, e) =>
                {
                    scroll2.ScrollToVerticalOffset(scroll1.VerticalOffset);
                };
                scroll2.ScrollChanged += (s, e) =>
                {
                    scroll1.ScrollToVerticalOffset(scroll2.VerticalOffset);
                };
            };
            Aggregator.GetEvent<ShowWindowEvent>().Subscribe(OnShowWindow, ThreadOption.UIThread);
        }

        public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);

                    if (child != null && child is T chi)
                        yield return chi;

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                        yield return childOfChild;
                }
            }
        }

        private void OnShowWindow()
        {
            this.Show();
            if (this.WindowState == WindowState.Minimized)
            {
                this.WindowState = WindowState.Maximized;
            }
            this.Activate();
        }

        private async void CheckAppVersion()
        {
            try
            {
                using (var client = new System.Net.Http.HttpClient())
                {
                    var app = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
                    var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(3);
                    var url = $"http://db.cnsos.net/get_app_version.php?app={app}&version={version}";
                    var result = await client.GetStringAsync(url);
                    if (result != version)
                    {
                        if (MessageBox.Show($"{Properties.Resources.ApplicationName}\r\n新版本：{result}\r\n当前版本：{version}\r\n点击【确认】打开程序文件夹", "发现新版本") == MessageBoxResult.OK)
                        {
                            await Process.Start("explorer.exe", System.AppDomain.CurrentDomain.BaseDirectory);
                            Application.Current.Shutdown();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
            }
        }
    }
}